var express = require('express');
var router = express.Router();
const {User,bookinfo,Laboratory,Equipment} = require('../../models')
const {success,failure} = require('../../util/requestResult')
const {NotFoundError,BadRequestError,UnauthorizedError,AlreadyExistsError,SequelizeValidateError} = require('../../util/errors')
// 查询条件限制
const condition = {
    include:[
        {
          model:User,
          as:'User',
          attributes:['id','account','name']
        },
        {
          model:Laboratory,
          as:'Laboratory',
          attributes:['id','laboratoryName']
        },
        {
          model:Equipment,
          as:'Equipment',
          attributes:['id','equipmentName']
        },
      ],
    exinclude:[]
}


// 按用户id查找用户的预定信息
router.get('/:id',async function(req,res,next){
    try {
        const conditions = {
            include:[
                {
                  model:User,
                  as:'User',
                  attributes:['id','account','name']
                },
                {
                  model:Laboratory,
                  as:'Laboratory',
                  attributes:['id','laboratoryName']
                },
                {
                  model:Equipment,
                  as:'Equipment',
                  attributes:['id','equipmentName']
                },
              ],
            where:{
                userId:req.params.id
            }
        }
        let bookinfos = await bookinfo.findAll(conditions)
        let data
        if(bookinfos instanceof Array)
            data = bookinfos
        else
            data = [bookinfos]
        success(res,`查询用户id为${req.params.id}的预定信息成功`,data)
    } catch (error) {
        failure(res,error)
    }

})

// 新增预定信息
router.post('/',async function(req,res,next){
    try {
        let bookinfoInfo = filterBody(req)
        let laboratory = await Laboratory.findByPk(bookinfo.bookLaboratoryId)
        let {max} = laboratory
        if(max == 0){
            throw new AlreadyExistsError("超过预约最大人数，不可预约");
        }
        let createdbookinfo = await bookinfo.create(bookinfoInfo)
        await laboratory.update({max:max-1})
        if(max-1 == 0){
            await laboratory.update({isApplyBook:0})
        }
        success(res,'创建预定信息成功',createdbookinfo,201)
    } catch (error) {
        failure(res,error)
    }

})

// 更新预定信息
router.put('/:id',async function(req,res,next){
    try {
        let bookinfoInfo = filterBody(req)
        let bookinfo = await getbookinfo(req)
        await bookinfo.update(bookinfoInfo)
        success(res,`更新id为${req.params.id}预定信息成功`,bookinfo)
    } catch (error) {
        failure(res,error)
    }

})


// 删除预定信息
router.delete('/:id',async function(req,res,next){
    try {
        let bookinfo = await getbookinfo(req)
        await bookinfo.destroy()
        success(res,`删除id为${req.params.id}预定信息成功`)
    } catch (error) {
        failure(res,error)
    }

})


function filterBody(req){
    let {bookLaboratoryId,bookEquipmentId,userId,startTime,endTime} = req.body
    return {bookLaboratoryId,bookEquipmentId,userId,startTime,endTime}
}


async function getbookinfo(req,isCondition){
    const {id} = req.params
    let bookinfos = await bookinfo.findByPk(id,isCondition?condition:{})
    if(!bookinfos)
        throw new NotFoundError(`未查询到id为${id}的预定信息`)
    return bookinfos
}

module.exports = router